package com.suredy.app.porject.service;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.suredy.app.porject.constants.MoneyType;
import com.suredy.app.porject.model.BidMoney;
import com.suredy.app.porject.model.FlowOfBid2User;
import com.suredy.core.service.BaseSrvWithEntity;
import com.suredy.security.entity.UserEntity;

@Service
public class BidMoneySrv extends BaseSrvWithEntity<BidMoney> {

	public BidMoneySrv() {
		this.addAnDefOrder("time", true);
		this.addAnDefOrder("name", true);
	}

	@Override
	public DetachedCriteria getDc(BidMoney t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null)
			return dc;

		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		if (t.getPayOut() != null) {
			dc.add(Restrictions.eq("payOut", t.getPayOut()));
		}
		if (t.getGaveBack() != null) {
			dc.add(Restrictions.eq("gaveBack", t.getGaveBack()));
		}
		if (!StringUtils.isBlank(t.getName())) {
			dc.add(Restrictions.eq("name", t.getName()));
		}
		if (!StringUtils.isBlank(t.getSource())) {
			dc.add(Restrictions.like("source", t.getSource(), MatchMode.ANYWHERE));
		}
		if (t.getBid() != null) {
			dc.add(Restrictions.eq("bid", t.getBid()));
		}

		return dc;
	}

	@Transactional
	public List<BidMoney> getNeedBackMoney(Date start, Date end, String userId) {
		BidMoney search = new BidMoney();
		search.setName(MoneyType.B_BZ.getValue());
		search.setGaveBack(false);

		DetachedCriteria dc = this.getDc(search);

		if (start != null)
			dc.add(Restrictions.ge("backTime", start));

		if (end != null)
			dc.add(Restrictions.le("backTime", end));

		DetachedCriteria bidDc = DetachedCriteria.forClass(FlowOfBid2User.class);
		bidDc.setProjection(Property.forName("bid"));

		bidDc.add(Restrictions.eq("user", new UserEntity(userId)));

		dc.add(Property.forName("bid").in(bidDc));

		@SuppressWarnings("unchecked")
		List<BidMoney> ret = (List<BidMoney>) this.readByCriteria(dc);

		if (ret == null || ret.isEmpty())
			return null;

		for (BidMoney m : ret) {
			m.getBid().getId();
		}

		return ret;
	}

}
